﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using System.Configuration;
using System.Web.Security;
using System.Collections;
using DevExpress.Web.ASPxCallback;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;

namespace TireService.Web.View.CustomerView
{
    public partial class EditCustomer : System.Web.UI.Page
    {
        #region Public Properties

        public int CustomerId
        {
            get
            {
                if (ViewState["_customerid"] != null)
                    return (int)ViewState["_customerid"];
                else
                    return 0;
            }
            set
            {
                ViewState["_customerid"] = value;
            }
        }

        public int CustomerSubscriptionId
        {
            get
            {
                if (ViewState["_customersubscriptionid"] != null)
                    return (int)ViewState["_customersubscriptionid"];
                else
                    return 0;
            }
            set
            {
                ViewState["_customersubscriptionid"] = value;
            }
        }

        public int CarId
        {
            get
            {
                if (ViewState["_carid"] != null)
                    return (int)ViewState["_carid"];
                else
                    return 0;
            }
            set
            {
                ViewState["_carid"] = value;
            }
        }

        public int TireSetId
        {
            get
            {
                if (ViewState["_tiresetid"] != null)
                    return (int)ViewState["_tiresetid"];
                else
                    return 0;
            }
            set
            {
                ViewState["_tiresetid"] = value;
            }
        }

        public List<int> EditCustomers
        {
            get
            {
                if (ViewState["_editcustomers"] != null)
                    return (List<int>)ViewState["_editcustomers"];
                else
                    return null;
            }
            set
            {
                ViewState["_editcustomers"] = value;
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            if (Page.IsPostBack != true)
            {
                #region Prepare data for editing

                // Prepare data for edit customer contact data
                ddlParentCompany.DataSource = db.GetParentCustomers();
                ddlParentCompany.ValueField = "CustomerId";
                ddlParentCompany.TextField = "CompanyName";
                ddlParentCompany.DataBind();

                ddlCountry.DataSource = db.GetCountries();
                ddlCountry.ValueField = "CountryId";
                ddlCountry.TextField = "CountryName";
                ddlCountry.DataBind();

                #endregion

                // Get multiedit id's
                if (Session["EditCustomers"] != null)
                {
                    this.EditCustomers = (List<int>)Session["EditCustomers"];
                    this.CustomerId = Convert.ToInt32(EditCustomers.First());
                }

                // Get customer id
                try
                {
                    // Get customer Id and save to propertie
                    if (Session["CustomerId"] != null) this.CustomerId = Convert.ToInt32(Session["CustomerId"]);
                    if (Request.QueryString["CustomerId"] != null)
                    {
                        this.CustomerId = Convert.ToInt32(Request.QueryString["CustomerId"]);
                    }
                }
                catch (Exception)
                {
                    // Nothing - invalid customerid, not an integer

                    // Reset customerid
                    this.CustomerId = 0;
                }
            }
            else
            {

            }

            bool MultiEdit = (this.EditCustomers != null);
            LoadCustomer(this.CustomerId, MultiEdit);

            // Dispose connection to database
            db.Dispose();
        }

        #region Private Functions

        /// <summary>
        /// Function that bind customer subscriptions to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        private void BindCustomerSubscription(TireServiceDB db, int CustomerId)
        {
            List<CustomerSubscriptionView> customersubscription = db.GetCustomerSubscriptionViews(CustomerId);
            //List<BusinessSubscriptionListView> customersubscription = db.GetCustomerBusinessSubscriptions(CustomerId);

            // Bind to gridview
            gvCustomerSubscription.DataSource = customersubscription;
            gvCustomerSubscription.DataBind();

            // Prepare data for editmode of customer subscription
            GridViewDataComboBoxColumn ddlSubscription = gvCustomerSubscription.Columns["SubscriptionDropdown"] as GridViewDataComboBoxColumn;
            ddlSubscription.PropertiesComboBox.ValueType = typeof(int);
            ddlSubscription.PropertiesComboBox.DataSource = db.GetSubscription();
            ddlSubscription.PropertiesComboBox.TextField = "Description";
            ddlSubscription.PropertiesComboBox.ValueField = "SubscriptionId";
            ddlSubscription.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlSubscription.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            // Prepare data for editmode of customer car
            GridViewDataComboBoxColumn ddlCarSubscription = gvCar.Columns["CustomerSubscriptionDropdown"] as GridViewDataComboBoxColumn;
            ddlCarSubscription.PropertiesComboBox.ValueType = typeof(int);
            ddlCarSubscription.PropertiesComboBox.DataSource = customersubscription;
            ddlCarSubscription.PropertiesComboBox.TextField = "Description";
            ddlCarSubscription.PropertiesComboBox.ValueField = "CustomerSubscriptionId";
            ddlCarSubscription.PropertiesComboBox.TextFormatString = "{0}-{1}";
        }

        /// <summary>
        /// Function that bind customer car to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="CustomerId">Id for customer</param>
        private void BindCustomerCar(TireServiceDB db, int CustomerId)
        {
            //List<Car> cars = db.GetCars(CustomerId);
            List<BusinessCarListView> cars = db.GetCustomerCarsAll(CustomerId, true); 

            // Bind to gridview
            gvCar.DataSource = cars;
            gvCar.DataBind();

            gvCar.ClearSort();
            gvCar.GroupSummary.Clear();
            gvCar.GroupBy(gvCar.Columns["CustomerSubscriptionId"]);
            gvCar.ExpandAll();

            // Prepare data for editmode of customer car
            GridViewDataComboBoxColumn ddlCarBrand = gvCar.Columns["CarBrandDropdown"] as GridViewDataComboBoxColumn;
            ddlCarBrand.PropertiesComboBox.ValueType = typeof(int);
            ddlCarBrand.PropertiesComboBox.DataSource = db.GetCarBrand();
            ddlCarBrand.PropertiesComboBox.TextField = "Description";
            ddlCarBrand.PropertiesComboBox.ValueField = "CarBrandId";
            ddlCarBrand.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlCarBrand.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlCarStatus = gvCar.Columns["CarStatusDropdown"] as GridViewDataComboBoxColumn;
            ddlCarStatus.PropertiesComboBox.ValueType = typeof(int);
            ddlCarStatus.PropertiesComboBox.DataSource = db.GetCarStatus();
            ddlCarStatus.PropertiesComboBox.TextField = "Description";
            ddlCarStatus.PropertiesComboBox.ValueField = "CarStatusId";
            ddlCarStatus.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlCarStatus.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlFuelType = gvCar.Columns["FuelTypeDropdown"] as GridViewDataComboBoxColumn;
            ddlFuelType.PropertiesComboBox.ValueType = typeof(int);
            ddlFuelType.PropertiesComboBox.Items.Clear();
            ddlFuelType.PropertiesComboBox.Items.Add("Benzin", 0);
            ddlFuelType.PropertiesComboBox.Items.Add("Diesel", 1);
            ddlFuelType.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlFuelType.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            // Prepare data for editmode of customer tireset
            GridViewDataComboBoxColumn ddlCar = gvTireSet.Columns["CarDropdown"] as GridViewDataComboBoxColumn;
            ddlCar.PropertiesComboBox.ValueType = typeof(int);
            ddlCar.PropertiesComboBox.Columns.Add("RegistrationNumber", "Reg.nr");
            ddlCar.PropertiesComboBox.Columns.Add("Model", "Model");
            ddlCar.PropertiesComboBox.Columns.Add("Year", "Årgang");
            ddlCar.PropertiesComboBox.Columns.Add("Color", "Farve");
            ddlCar.PropertiesComboBox.DataSource = cars;
            //ddlCar.PropertiesComboBox.TextField = "Description";
            ddlCar.PropertiesComboBox.ValueField = "CarId";
            ddlCar.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlCar.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

        }

        /// <summary>
        /// Function that bind tireset data to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="CustomerId">Id on customer</param>
        private void BindTireSet(TireServiceDB db, int CustomerId)
        {
            //gvTireSet.DataSource = db.GetCarTireSetViews(CustomerId);
            gvTireSet.DataSource = db.GetCustomerTireSets(CustomerId, true);
            gvTireSet.DataBind();

            // Prepare data for editmode of tireset 
            GridViewDataComboBoxColumn ddlTireType = gvTireSet.Columns["TireTypeDropdown"] as GridViewDataComboBoxColumn;
            ddlTireType.PropertiesComboBox.ValueType = typeof(int);
            ddlTireType.PropertiesComboBox.DataSource = db.GetTireType();
            ddlTireType.PropertiesComboBox.TextField = "Description";
            ddlTireType.PropertiesComboBox.ValueField = "TireTypeId";
            ddlTireType.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlTireType.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlTireSpeedIndex = gvTireSet.Columns["TireSpeedIndexDropdown"] as GridViewDataComboBoxColumn;
            ddlTireSpeedIndex.PropertiesComboBox.ValueType = typeof(int);
            ddlTireSpeedIndex.PropertiesComboBox.DataSource = db.GetTireSpeedIndex();
            ddlTireSpeedIndex.PropertiesComboBox.TextField = "Description";
            ddlTireSpeedIndex.PropertiesComboBox.ValueField = "TireSpeedIndexId";
            ddlTireSpeedIndex.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlTireSpeedIndex.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlTireLoadIndex = gvTireSet.Columns["TireLoadIndexDropdown"] as GridViewDataComboBoxColumn;
            ddlTireLoadIndex.PropertiesComboBox.ValueType = typeof(int);
            ddlTireLoadIndex.PropertiesComboBox.DataSource = db.GetTireLoadIndex();
            ddlTireLoadIndex.PropertiesComboBox.TextField = "Description";
            ddlTireLoadIndex.PropertiesComboBox.ValueField = "TireLoadIndexId";
            ddlTireLoadIndex.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlTireLoadIndex.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlTireBrand = gvTireSet.Columns["TireBrandDropdown"] as GridViewDataComboBoxColumn;
            ddlTireBrand.PropertiesComboBox.ValueType = typeof(int);
            ddlTireBrand.PropertiesComboBox.DataSource = db.GetTireBrands();
            ddlTireBrand.PropertiesComboBox.TextField = "Description";
            ddlTireBrand.PropertiesComboBox.ValueField = "TireBrandId";
            ddlTireBrand.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlTireBrand.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlTireSetStatus = gvTireSet.Columns["TireSetStatusDropdown"] as GridViewDataComboBoxColumn;
            ddlTireSetStatus.PropertiesComboBox.ValueType = typeof(int);
            ddlTireSetStatus.PropertiesComboBox.DataSource = db.GetTireSetStatus();
            ddlTireSetStatus.PropertiesComboBox.TextField = "Description";
            ddlTireSetStatus.PropertiesComboBox.ValueField = "TireSetStatusId";
            ddlTireSetStatus.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlTireSetStatus.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlSize = gvTireSet.Columns["SizeDropdown"] as GridViewDataComboBoxColumn;
            ddlSize.PropertiesComboBox.ValueType = typeof(decimal);
            ddlSize.PropertiesComboBox.Items.Add("8,0");
            ddlSize.PropertiesComboBox.Items.Add("9,0");
            ddlSize.PropertiesComboBox.Items.Add("10,0");
            ddlSize.PropertiesComboBox.Items.Add("12,0");
            ddlSize.PropertiesComboBox.Items.Add("13,0");
            ddlSize.PropertiesComboBox.Items.Add("14,0");
            ddlSize.PropertiesComboBox.Items.Add("15,0");
            ddlSize.PropertiesComboBox.Items.Add("16,0");
            ddlSize.PropertiesComboBox.Items.Add("17,0");
            ddlSize.PropertiesComboBox.Items.Add("17,5");
            ddlSize.PropertiesComboBox.Items.Add("18,0");
            ddlSize.PropertiesComboBox.Items.Add("19,0");
            ddlSize.PropertiesComboBox.Items.Add("20,0");
            ddlSize.PropertiesComboBox.Items.Add("21,0");
            ddlSize.PropertiesComboBox.Items.Add("22,0");
            ddlSize.PropertiesComboBox.Items.Add("23,0");
            ddlSize.PropertiesComboBox.Items.Add("24,0");
            ddlSize.PropertiesComboBox.Items.Add("48,0");
            ddlSize.PropertiesComboBox.Items.Add("390,0");
            ddlSize.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlSize.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlWidth = gvTireSet.Columns["WidthDropdown"] as GridViewDataComboBoxColumn;
            ddlWidth.PropertiesComboBox.ValueType = typeof(decimal);
            ddlWidth.PropertiesComboBox.Items.Add("125,0");
            ddlWidth.PropertiesComboBox.Items.Add("135,0");
            ddlWidth.PropertiesComboBox.Items.Add("140,0");
            ddlWidth.PropertiesComboBox.Items.Add("145,0");
            ddlWidth.PropertiesComboBox.Items.Add("155,0");
            ddlWidth.PropertiesComboBox.Items.Add("165,0");
            ddlWidth.PropertiesComboBox.Items.Add("175,0");
            ddlWidth.PropertiesComboBox.Items.Add("185,0");
            ddlWidth.PropertiesComboBox.Items.Add("195,0");
            ddlWidth.PropertiesComboBox.Items.Add("205,0");
            ddlWidth.PropertiesComboBox.Items.Add("215,0");
            ddlWidth.PropertiesComboBox.Items.Add("225,0");
            ddlWidth.PropertiesComboBox.Items.Add("230,0");
            ddlWidth.PropertiesComboBox.Items.Add("235,0");
            ddlWidth.PropertiesComboBox.Items.Add("245,0");
            ddlWidth.PropertiesComboBox.Items.Add("255,0");
            ddlWidth.PropertiesComboBox.Items.Add("265,0");
            ddlWidth.PropertiesComboBox.Items.Add("275,0");
            ddlWidth.PropertiesComboBox.Items.Add("285,0");
            ddlWidth.PropertiesComboBox.Items.Add("295,0");
            ddlWidth.PropertiesComboBox.Items.Add("305,0");
            ddlWidth.PropertiesComboBox.Items.Add("315,0");
            ddlWidth.PropertiesComboBox.Items.Add("325,0");
            ddlWidth.PropertiesComboBox.Items.Add("335,0");
            ddlWidth.PropertiesComboBox.Items.Add("345,0");
            ddlWidth.PropertiesComboBox.Items.Add("375,0");
            ddlWidth.PropertiesComboBox.Items.Add("600,0");
            ddlWidth.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlWidth.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlHeight = gvTireSet.Columns["HeightDropdown"] as GridViewDataComboBoxColumn;
            ddlHeight.PropertiesComboBox.ValueType = typeof(decimal);
            ddlHeight.PropertiesComboBox.Items.Add("25,0");
            ddlHeight.PropertiesComboBox.Items.Add("30,0");
            ddlHeight.PropertiesComboBox.Items.Add("35,0");
            ddlHeight.PropertiesComboBox.Items.Add("40,0");
            ddlHeight.PropertiesComboBox.Items.Add("45,0");
            ddlHeight.PropertiesComboBox.Items.Add("50,0");
            ddlHeight.PropertiesComboBox.Items.Add("55,0");
            ddlHeight.PropertiesComboBox.Items.Add("60,0");
            ddlHeight.PropertiesComboBox.Items.Add("65,0");
            ddlHeight.PropertiesComboBox.Items.Add("70,0");
            ddlHeight.PropertiesComboBox.Items.Add("75,0");
            ddlHeight.PropertiesComboBox.Items.Add("80,0");
            ddlHeight.PropertiesComboBox.Items.Add("85,0");
            ddlHeight.PropertiesComboBox.Items.Add("95,0");
            ddlHeight.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlHeight.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            gvTireSet.ClearSort();
            gvTireSet.GroupSummary.Clear();
            gvTireSet.GroupBy(gvTireSet.Columns["CarBrandDescription"]);
            gvTireSet.GroupBy(gvTireSet.Columns["Model"]);
            gvTireSet.ExpandAll();
        }

        /// <summary>
        /// Function that bind email log data to gridview
        /// </summary>
        /// <param name="db"></param>
        /// <param name="CustomerId"></param>
        private void BindEmailLog(TireServiceDB db, int CustomerId)
        {
            gvCustomerEmailLog.DataSource = db.GetCustomerBusinessEmailLogs(CustomerId, true);
            gvCustomerEmailLog.DataBind();
        }

        /// <summary>
        /// Function that load customer and change UI
        /// </summary>
        /// <param name="CustomerId">Id for customer to load</param>
        /// <param name="MultiEdit">True/false value to change UI for multiedit or not</param>
        protected void LoadCustomer(int CustomerId, bool MultiEdit)
        {
            // Set page propertie
            this.CustomerId = CustomerId;

            TireServiceDB db = new TireServiceDB();

            if (CustomerId != 0)
            {
                // Bind item data to editform
                Customer customer = new Customer();
                customer = db.GetCustomer(CustomerId);

                if (customer != null)
                {
                    // Set form fields
                    // Customer info
                    lblCustomerNumberValue.Text = customer.CustomerId.ToString();

                    if (customer.ParentCustomerId != null)
                    {
                        ddlParentCompany.Items.FindByValue(Convert.ToString(customer.ParentCustomerId)).Selected = true;
                        pParentCompany.Visible = true;
                    }
                    else
                    {
                        pParentCompany.Visible = false;
                    }
                    pIsCompany.Visible = customer.IsCompany;
                    cbParentPayInvoice.Checked = customer.ParentPayInvoice;
                    txtCompanyName.Text = customer.CompanyName;
                    txtCompanyNumber.Text = customer.CompanyNumber;

                    txtName.Text = customer.Name;
                    txtAddress.Text = customer.Address;
                    txtZipCode.Text = customer.ZipCode;
                    txtCity.Text = customer.City;
                    ddlCountry.Items.FindByValue(Convert.ToString(customer.CountryId)).Selected = true;
                    txtSecondaryAddress.Text = customer.SecondaryAddress;
                    txtSecondaryZipCode.Text = customer.SecondaryZipCode;
                    txtSecondaryCity.Text = customer.SecondaryCity;
                    txtPhone1.Text = customer.Phone1;
                    ddlPhone1Type.Items.FindByValue(Convert.ToString(customer.Phone1Type)).Selected = true;
                    if (customer.Phone2 != null) txtPhone2.Text = customer.Phone2;
                    if (customer.Phone2 != null) ddlPhone2Type.Items.FindByValue(Convert.ToString(customer.Phone2Type)).Selected = true;
                    txtEmail.Text = customer.Email;
                    rbPrimaryAddressTimeInterval.Value = (object)customer.OnPrimaryAddressInPrimeTime;
                    cbEconomicSync.Checked = customer.SyncToEconomic;

                    // Load invoices from e-conomic
                    EconomicInterface ecoInterface = new EconomicInterface();
                    gvInvoice.DataSource = ecoInterface.GetCustomerInvoiceList(customer.CustomerId); //db.GetCustomerInvoices(this.CustomerId);
                    gvInvoice.DataBind();

                    // Load planned/past service details
                    gvService.DataSource = db.GetCustomerService(customer.CustomerId, true);
                    gvService.DataBind();

                    // Load subdepartments
                    gvCustomer.DataSource = db.GetCustomersForParentCustomerView(customer.CustomerId);
                    gvCustomer.DataBind();
                }
                else
                {
                    // Customer NOT found - set UI for create customer
                    this.CustomerId = 0;
                    ResetEditCustomer();
                }
            }

            // Show/hide sync with economic checkbox
            cbEconomicSync.Enabled = (this.CustomerId == 0);

            // Fetch related data for Customer
            BindCustomerSubscription(db, CustomerId);
            BindCustomerCar(db, CustomerId);
            BindTireSet(db, CustomerId);
            BindEmailLog(db, CustomerId);

            // Change UI based on multiedit input
            ChangeMultiEdit(MultiEdit, CustomerId);

            // Dispose connection to database
            db.Dispose();
        }

        /// <summary>
        /// Function that change UI based on multiediting on/off
        /// </summary>
        /// <param name="MultiEdit">True/false value indicating if multiedit is on/off</param>
        /// <param name="CustomerId">Id for customer being edited</param>
        protected void ChangeMultiEdit(bool MultiEdit, int CustomerId)
        {
            // Change UI for multiedit
            if (MultiEdit)
            {
                // Show index number and total numbers of contact to edit
                lblMultiEdit.Text = "&nbsp;|&nbsp;Rediger flere kunder: " + (this.EditCustomers.IndexOf(CustomerId) + 1).ToString() + " af " + this.EditCustomers.Count.ToString();

                // Change buttons
                btnSaveCustomerClose.Text = "Gem og afslut";
                btnSaveCustomer.Text = "Gem og gå til næste";
                lbtnNextCustomer.Enabled = (CustomerId != (int)this.EditCustomers.Last());
                lbtnPreviousCustomer.Enabled = (CustomerId != (int)this.EditCustomers.First());
            }
            else
            {
                btnSaveCustomer.Text = "Gem";
                lbtnNextCustomer.Visible = false;
                lbtnPreviousCustomer.Visible = false;
            }
            lbtnNextCustomer.Visible = MultiEdit;
            lbtnPreviousCustomer.Visible = MultiEdit;
            btnSaveCustomerClose.Visible = MultiEdit;
            lblMultiEdit.Visible = MultiEdit;
        }

        /// <summary>
        /// Function that reset/clears edit item form
        /// </summary>
        protected void ResetEditCustomer()
        {
            // Clear properties
            this.CustomerId = 0;
            Session["CustomerId"] = null;

            if (this.EditCustomers != null)
            {
                List<int> _editcustomer = new List<int>();
                _editcustomer.Clear();

                this.EditCustomers = _editcustomer;

                Session["EditCustomers"] = null;
            }

            // Clear form fields
            lblCustomerNumberValue.Text = "";
            ddlParentCompany.SelectedIndex = -1;
            pParentCompany.Visible = false;
            cbParentPayInvoice.Checked = false;
            
            cbIsCompany.Checked = false;
            pIsCompany.Visible = false;
            txtCompanyName.Text = "";
            txtCompanyNumber.Text = "";
            
            txtName.Text = "";
            txtAddress.Text = "";
            txtZipCode.Text = "";
            txtCity.Text = "";
            txtSecondaryAddress.Text = "";
            txtSecondaryZipCode.Text = "";
            txtSecondaryCity.Text = "";
            txtPhone1.Text = "";
            txtPhone2.Text = "";
            txtEmail.Text = "";
            rbPrimaryAddressTimeInterval.Value = "";
            
            // Hide multiedit buttons
            lbtnNextCustomer.Visible = false;
            lbtnPreviousCustomer.Visible = false;
            btnSaveCustomerClose.Visible = false;
            lblMultiEdit.Visible = false;

            // Change multiedit UI
            ChangeMultiEdit(false, this.CustomerId);

            TireServiceDB db = new TireServiceDB();

            // Refresh/bind tab field data
            BindCustomerSubscription(db, this.CustomerId);
            BindCustomerCar(db, this.CustomerId);
            BindTireSet(db, this.CustomerId);

            db.Dispose();
        }

        /// <summary>
        /// Function that saves customer
        /// </summary>
        protected void SaveCustomer()
        {
            TireServiceDB db = new TireServiceDB();

            // Create customer
            Customer customer = new Customer();

            bool parentcompany = false;
            int? parentcustomerid = null;
            bool parentpayinvoice = false;
            string companyname = null;
            string companynumber = null;
            int? phone2type = null;

            if (ddlParentCompany.SelectedItem != null)
            {
                parentcompany = true;
                parentcustomerid = Convert.ToInt32(ddlParentCompany.SelectedItem.Value);
                parentpayinvoice = cbParentPayInvoice.Checked;
            }

            if (cbIsCompany.Checked)
            {
                companyname = txtCompanyName.Text;
                companynumber = txtCompanyNumber.Text;
            }

            if (ddlPhone2Type.SelectedItem != null)
            {
                phone2type = Convert.ToInt32(ddlPhone2Type.SelectedItem.Value);
            }

            CustomerBLL customerBLL = new CustomerBLL();
            customerBLL.UpdateCustomer(
                                        db,
                                        customer,
                                        this.CustomerId,
                                        parentcompany,
                                        parentcustomerid,
                                        parentpayinvoice,
                                        cbIsCompany.Checked,
                                        companyname,
                                        companynumber,
                                        txtName.Text,
                                        txtAddress.Text,
                                        txtZipCode.Text,
                                        txtCity.Text,
                                        Convert.ToInt32(ddlCountry.Value),
                                        txtSecondaryAddress.Text,
                                        txtSecondaryZipCode.Text,
                                        txtSecondaryCity.Text,
                                        txtPhone1.Text,
                                        Convert.ToInt32(ddlPhone1Type.Value),
                                        txtPhone2.Text,
                                        phone2type,
                                        txtEmail.Text,
                                        Convert.ToBoolean(Convert.ToByte(rbPrimaryAddressTimeInterval.Value)),
                                        cbEconomicSync.Checked,
                                        false, // Manual Invocing - TODO: Improve
                                        false, // PBS Invocing - TODO: Improve
                                        false
                                    );

            //// Submit changes to database
            //db.SubmitChanges();

            // Set page properties
            this.CustomerId = customer.CustomerId;
        }

        /// <summary>
        /// Function that runs specific actions for customer
        /// </summary>
        /// <param name="Action">Id for action to run</param>
        protected void SubmitAction(int Action)
        {
            if (Action == 0)
            {
                throw new ArgumentException("Ingen handling valgt.");
            }
            if (Action == 1)
            {
                // Create user and send email
                CreateUserLogin(true);
            }
            if (Action == 2)
            {
                // Create user without sending login details
                CreateUserLogin(false);
            }
            if (Action == 3)
            {
                // Send login details to user
                if (this.CustomerId != 0)
                {
                    TireServiceDB db = new TireServiceDB();

                    // Fetch customer
                    Customer customer = db.GetCustomer(this.CustomerId);

                    if (customer.UserId != null)
                    {
                        MembershipUser user = Membership.GetUser(new Guid(customer.UserId.ToString())); //(object)customer.UserId);

                        // Send email to user with user information
                        EmailNotificationServices emailService = new EmailNotificationServices();
                        emailService.UserInformation_SendCustomerEmail(customer.Email, customer.Name, user.UserName, customer.Phone1.ToString(), this.CustomerId);
                        //SendEmailUserInfo(customer.Email, customer.Name, user.UserName, user.GetPassword(), this.CustomerId, userid);

                        // Userlogin send to customer
                        throw new ArgumentException("Brugerlogin sendt til kunde.");
                    }
                    else
                    {
                        throw new ArgumentException("Kunde har intet brugerlogin.");
                    }
                }
                else
                {
                    throw new ArgumentException("Brugerlogin eksisterer ikke - venligst opret kunde først.");
                }
            }
        }

        private void CreateUserLogin(bool SendEmail)
        {
            if (this.CustomerId != 0)
            {
                TireServiceDB db = new TireServiceDB();

                // Fetch customer
                Customer customer = db.GetCustomer(this.CustomerId);

                if (customer.UserId != null)
                {
                    // User already exist for customer
                    throw new ArgumentException("Kunde har allerede brugerlogin.");
                }
                else
                {
                    // Create user and send login details
                    MembershipUser user = Membership.CreateUser(customer.Email, customer.Phone1.ToString(), customer.Email);

                    // Add user to customer role
                    Roles.AddUserToRole(user.UserName, "Kunde");

                    customer.UserId = new Guid(user.ProviderUserKey.ToString());

                    db.SubmitChanges();

                    if (SendEmail)
                    {
                        // Send email to user with user information
                        EmailNotificationServices emailService = new EmailNotificationServices();
                        emailService.UserInformation_SendCustomerEmail(customer.Email, customer.Name, user.UserName, customer.Phone1.ToString(), this.CustomerId);
                        //SendEmailUserInfo(customer.Email, customer.Name, user.UserName, customer.Phone1.ToString(), this.CustomerId, userid);

                        throw new ArgumentException("Brugerlogin oprettet og oplysninger sendt til kunde.");
                    }
                    else
                    {
                        throw new ArgumentException("Brugerlogin oprettet.");
                    }
                }
            }
            else
            {
                throw new ArgumentException("Brugerlogin kan ikke oprettes før kunde data er gemt.");
            }
        }

        ///// <summary>
        ///// Function that sends email to customer with userlogin details
        ///// </summary>
        ///// <param name="CustomerEmail">Customer email</param>
        ///// <param name="CustomerName">Name of customer</param>
        ///// <param name="UserName">Username</param>
        ///// <param name="Password">Password</param>
        ///// <param name="CustomerId">Id on customer</param>
        ///// <param name="UserId">Id on user executing action</param>
        //private void SendEmailUserInfo(string CustomerEmail, string CustomerName, string UserName, string Password, int CustomerId, Guid UserId)
        //{
        //    string Subject = "Brugerlogin til mobilhjulskift.dk";
        //    bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));

        //    EmailNotification.EmailNotification message = new EmailNotification.EmailNotification();

        //    Shared email = new Shared();

        //    // Send email to customer with us on bcc
        //    email.SendEmail(CustomerEmail, ConfigurationManager.AppSettings["EmailAddress"].ToString(), message.SendEmailUserInfoStandard(CustomerName, UserName, Password), Subject, true, test, ConfigurationManager.AppSettings["EmailAddress"].ToString(), null, null);
        //}

        ///// <summary>
        ///// Function that sends email to customer with order confirmation on signup
        ///// </summary>
        ///// <param name="CustomerEmail">Customer email that this email will be send to</param>
        ///// <param name="CustomerName">Name on customer</param>
        ///// <param name="SubscriptionNumber">Unik subscription number (CustomerId-SubscriptionId)</param>
        ///// <param name="InvoiceId">Unik Guid number for invoice</param>
        ///// <param name="SubscriptionId">Unik Guid number for invoice</param>
        //private void SendInvoiceByEmail(string CustomerEmail, string CustomerName, string SubscriptionNumber, string InvoiceGuid, int SubscriptionId, int CustomerId, Guid UserId)
        //{
        //    string Subject = "Bestilling gennemført - Abonnement " + SubscriptionNumber;
        //    bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));

        //    EmailNotification.EmailNotification message = new EmailNotification.EmailNotification();

        //    Shared email = new Shared();

        //    Hashtable templateVars = new Hashtable();

        //    if (SubscriptionId == 4)
        //    {
        //        Subject = "Bestilling af enkelt hjulskift gennemført - bestillingsnr " + SubscriptionNumber;
        //    }

        //    // Send email to customer with us on bcc
        //    email.SendEmail(CustomerEmail, ConfigurationManager.AppSettings["EmailAddress"].ToString(), message.SendCustomerSubscriptionOrderConfirmation(CustomerName, SubscriptionNumber, InvoiceGuid, SubscriptionId), Subject, true, test, ConfigurationManager.AppSettings["EmailAddress"].ToString(), null, null, CustomerId, UserId);
        //}

        /// <summary>
        /// Function that redirects to list with all customers
        /// </summary>
        protected void GoToCustomerList()
        {
            // Reset edit customer session
            Session["CustomerId"] = null;
            Session["EditCustomers"] = null;

            // Redirect to list with all customers
            Response.Redirect("~/View/CustomerView/CustomerList.aspx");
        }
        
        #endregion

        #region Control Functions

        /// <summary>
        /// Button function that submit possible actions for page
        /// </summary>
        protected void btnSubmitAction_Click(object sender, EventArgs e)
        {
            try
            {
                // Execute selected action
                SubmitAction(Convert.ToInt32(ddlAction.SelectedValue));
            }
            catch (Exception ex)
            {
                if ((ex) is ArgumentException)
                {
                    // User error - arguments not valid - show error message
                    lMessage.Text = ((ArgumentException)ex).Message;
                }
                else
                {
                    // System error - show general error message
                    lMessage.Text = "Fejl opstod - venligst prøv igen";
                }
            }
            finally
            {
                // Update message panel
                upMessage.Update();
            }

        }

        /// <summary>
        /// Button function that reset edit form for creating a new customer
        /// </summary>
        protected void btnNewCustomer_Click(object sender, EventArgs e)
        {
            try
            {
                // Reset ALL edit forms
                ResetEditCustomer();

                // Update/reset message
                lMessage.Text = "";
            }
            catch (Exception ex)
            {
                if ((ex) is ArgumentException)
                {
                    // User error - arguments not valid - show error message
                    lMessage.Text = ((ArgumentException)ex).Message;
                }
                else
                {
                    // System error - show general error message
                    lMessage.Text = "Fejl opstod - venligst prøv igen";
                }
            }
            finally
            {
                // Update message panel
                upMessage.Update();
            }
        }

        /// <summary>
        /// Button function that moves to edit of next customer when multiediting
        /// </summary>
        protected void lbtnNextCustomer_Click(object sender, EventArgs e)
        {
            try
            {
                // Move index forward
                LoadCustomer(this.EditCustomers.ElementAt((this.EditCustomers.IndexOf(this.CustomerId) + 1)), true);

                // Update message
                lMessage.Text = "";
            }
            catch (Exception ex)
            {
                if ((ex) is ArgumentException)
                {
                    // User error - arguments not valid - show error message
                    lMessage.Text = ((ArgumentException)ex).Message;
                }
                else
                {
                    // System error - show general error message
                    lMessage.Text = "Fejl opstod - venligst prøv igen";
                }
            }
            finally
            {
                // Update message panel
                upMessage.Update();
            }
        }

        /// <summary>
        /// Button function that moves to edit of previous customer when multiediting
        /// </summary>
        protected void lbtnPreviousCustomer_Click(object sender, EventArgs e)
        {
            try
            {
                // Move index backward
                LoadCustomer(this.EditCustomers.ElementAt((this.EditCustomers.IndexOf(this.CustomerId) - 1)), true);

                // Update message
                lMessage.Text = "";
            }
            catch (Exception ex)
            {
                if ((ex) is ArgumentException)
                {
                    // User error - arguments not valid - show error message
                    lMessage.Text = ((ArgumentException)ex).Message;
                }
                else
                {
                    // System error - show general error message
                    lMessage.Text = "Fejl opstod - venligst prøv igen";
                }
            }
            finally
            {
                // Update message panel
                upMessage.Update();
            }
        }

        /// <summary>
        /// Button function that saves customer
        /// </summary>
        protected void btnSaveCustomer_Click(object sender, EventArgs e)
        {
            try
            {
                // Save customer
                SaveCustomer();

                // Change message
                lMessage.Text = "Kunde blev gemt";

                // Check for multiedit
                if (this.EditCustomers != null)
                {
                    if (this.EditCustomers.Count > 1)
                    {
                        if (this.EditCustomers.IndexOf(this.CustomerId) != (this.EditCustomers.Count - 1))
                        {
                            // Go to edit mode for next contact in multiedit list
                            LoadCustomer(this.EditCustomers.ElementAt((this.EditCustomers.IndexOf(this.CustomerId) + 1)), true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if ((ex) is ArgumentException)
                {
                    // User error - arguments not valid - show error message
                    lMessage.Text = ((ArgumentException)ex).Message;
                }
                else
                {
                    // System error - show general error message
                    lMessage.Text = "Fejl opstod - venligst prøv igen";
                }
            }
            finally
            {
                // Update message panel
                upMessage.Update();
            }
        }

        /// <summary>
        /// Button function that saves customer and closes edit screen and return to customer overview
        /// </summary>
        protected void btnSaveCustomerClose_Click(object sender, EventArgs e)
        {
            try
            {
                // Save customer
                SaveCustomer();

                // Go to list with all customer
                GoToCustomerList();
            }
            catch (Exception ex)
            {
                if ((ex) is ArgumentException)
                {
                    // User error - arguments not valid - show error message
                    lMessage.Text = ((ArgumentException)ex).Message;
                }
                else
                {
                    // System error - show general error message
                    lMessage.Text = "Fejl opstod - venligst prøv igen";
                }
            }
            finally
            {
                // Update message panel
                upMessage.Update();
            }
        }

        /// <summary>
        /// Dropdownlist function that updates UI based on selected parent company value
        /// </summary>
        protected void ddlParentCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            pParentCompany.Visible = (ddlParentCompany.SelectedItem != null);
        }

        /// <summary>
        /// Checkbox function that updates UI based on is company is checked
        /// </summary>
        protected void cbIsCompany_CheckedChanged(object sender, EventArgs e)
        {
            pIsCompany.Visible = (cbIsCompany.Checked);
        }

        ///// <summary>
        ///// Button function that hides email message
        ///// </summary>
        //protected void btnCloseMessage_Click(object sender, EventArgs e)
        //{
        //    lEmailMessage.Visible = false;
        //    btnCloseMessage.Visible = false;
        //}

        /// <summary>
        /// Button function that send user to planning for selected cars in gridview
        /// </summary>
        protected void btnCreateServiceBooking_Click(object sender, EventArgs e)
        {
            try
            {
                List<object> keyValues = gvCar.GetSelectedFieldValues("CarId");

                if (keyValues.Count != 0)
                {
                    int[] selectedcars = new int[keyValues.Count];
                    int i = 0;
                    // Change invoice status to paid for selected invoices
                    foreach (object key in keyValues)
                    {
                        selectedcars[i] = Convert.ToInt32(key);
                        i += 1;
                    }

                    Session["SelectedCars"] = selectedcars;

                    Response.Redirect("~/View/ServiceView/Planning.aspx");
                }
                else
                {
                    throw new ArgumentException("Ingen biler valgt.");
                }
            }
            catch (Exception ex)
            {
                if ((ex) is ArgumentException)
                {
                    // User error - arguments not valid - show error message
                    lMessage.Text = ((ArgumentException)ex).Message;
                }
                else
                {
                    // System error - show general error message
                    lMessage.Text = "Fejl opstod - venligst prøv igen";
                }
            }
            finally
            {
                // Update message panel
                upMessage.Update();
            }
        }

        #endregion

        #region GridView Functions

        /// <summary>
        /// Gridview function that change field data for unbound fields
        /// </summary>
        protected void gvCustomer_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            // Format UnBoundColumn Type: Show country name
            if (e.Column.FieldName == "CountryName")
            {
                // Get countryid
                int countryid = Convert.ToInt32(e.GetListSourceFieldValue("CountryId"));

                TireServiceDB db = new TireServiceDB();

                // Change field value
                e.Value = db.GetCountryName(countryid);

                db.Dispose();
            }
        }

        /// <summary>
        /// Gridview function that handles edit selection of customer subscriptions
        /// </summary>
        protected void gvCustomerEmailLog_CustomButtonCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            //if (e.ButtonID == "ShowMessage")
            //{
            //    try
            //    {
            //        // Set email message
            //        lEmailMessage.Text = Convert.ToString(gvCustomerEmailLog.GetRowValues(e.VisibleIndex, "Message"));
            //        lEmailMessage.Visible = true;
            //        btnCloseMessage.Visible = true;
            //    }
            //    catch (Exception ex)
            //    {
            //        if ((ex) is ArgumentException)
            //        {
            //            // User error - arguments not valid - show error message
            //            lMessage.Text = ((ArgumentException)ex).Message;
            //        }
            //        else
            //        {
            //            // System error - show general error message
            //            lMessage.Text = "Fejl opstod - venligst prøv igen";
            //        }
            //    }
            //    finally
            //    {
            //        // Update message panel
            //        upMessage.Update();
            //    }
            //}
        }

        /// <summary>
        /// Gridview function for updating customer subscription
        /// </summary>
        protected void gvCustomerSubscription_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            if (this.CustomerId != 0)
            {
                TireServiceDB db = new TireServiceDB();

                // Get id
                this.CustomerSubscriptionId = Convert.ToInt32(e.Keys["CustomerSubscriptionId"]);

                CustomerSubscription customersubscription = new CustomerSubscription();

                // Fetch customer
                Customer customer = db.GetCustomer(this.CustomerId);

                Guid userid = new Guid(Membership.GetUser().ProviderUserKey.ToString());

                // Create customer subscription
                CustomerSubscriptionBLL customersubscriptionBLL = new CustomerSubscriptionBLL();
                customersubscriptionBLL.UpdateCustomerSubscription(
                    db,
                    customersubscription,
                    customer,
                    this.CustomerSubscriptionId,
                    Convert.ToInt32(e.NewValues["SubscriptionId"]),
                    Convert.ToDateTime(e.NewValues["LastRenewalDate"]),
                    Convert.ToDateTime(e.NewValues["NextRenewalDate"]),
                    Convert.ToBoolean(e.NewValues["InActive"]),
                    Convert.ToBoolean(e.NewValues["BalancingIncluded"]),
                    Convert.ToDecimal(e.NewValues["Price"]),
                    userid,
                    false,
                    "Redigering af abonnement"
                );

                //// Commit changes to database
                //db.SubmitChanges();

                // End edit mode
                e.Cancel = true;
                gvCustomerSubscription.CancelEdit();

                // Reset edit mode
                this.CustomerSubscriptionId = 0;

                // Refresh gridview
                BindCustomerSubscription(db, this.CustomerId);

                // Close db connection
                db.Dispose();
            }
            else
            {
                // Customer not yet saved
                throw new InvalidOperationException("Kunde data ikke gemt endnu - kunde abonnement kan derfor ikke oprettes. Venligst gem kundedata først.");
            }
        }

        /// <summary>
        /// Gridview function for creating customer subscription
        /// </summary>
        protected void gvCustomerSubscription_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            
            if (this.CustomerId != 0)
            {
                TireServiceDB db = new TireServiceDB();

                // Reset id
                this.CustomerSubscriptionId = 0;

                CustomerSubscription customersubscription = new CustomerSubscription();

                // Fetch customer
                Customer customer = db.GetCustomer(this.CustomerId);

                Guid userid = new Guid(Membership.GetUser().ProviderUserKey.ToString());

                // Create customer subscription
                CustomerSubscriptionBLL customersubscriptionBLL = new CustomerSubscriptionBLL();
                customersubscriptionBLL.UpdateCustomerSubscription(
                    db,
                    customersubscription,
                    customer,
                    this.CustomerSubscriptionId,
                    Convert.ToInt32(e.NewValues["SubscriptionId"]),
                    Convert.ToDateTime(e.NewValues["LastRenewalDate"]),
                    Convert.ToDateTime(e.NewValues["NextRenewalDate"]),
                    Convert.ToBoolean(e.NewValues["InActive"]),
                    Convert.ToBoolean(e.NewValues["BalancingIncluded"]),
                    Convert.ToDecimal(e.NewValues["Price"]),
                    userid,
                    false,
                    "Oprettelse af abonnement"
                );
                    
                // Check if invoice needs to be created
                ASPxCheckBox cbGenerateInvoice = (ASPxCheckBox)gvCustomerSubscription.FindEditFormTemplateControl("cbGenerateInvoice");
                ASPxCheckBox cbEmailInvoice = (ASPxCheckBox)gvCustomerSubscription.FindEditFormTemplateControl("cbEmailInvoice");

                // Create invoice selected
                if (cbGenerateInvoice.Checked)
                {
                    int customerid_invoiced = customer.CustomerId;

                    // Check if invoice is paid by parent customer
                    if (customer.ParentPayInvoice & customer.ParentCustomerId != null)
                    {
                        customerid_invoiced = Convert.ToInt32(customer.ParentCustomerId);
                    }

                    // Initiate Economic interface
                    EconomicInterface ecoInterface = new EconomicInterface();

                    // Create subscription invoice in E-conomic
                    string invoiceid = ecoInterface.CreateSubscriptionInvoice(db, customerid_invoiced, customersubscription, customersubscription.Price);

                    if (cbEmailInvoice.Checked)
                    {
                        // TODO: Create email with invoiceid    
                    }
                    
                }

                //// Commit changes to database
                //db.SubmitChanges();

                // End edit mode
                e.Cancel = true;
                gvCustomerSubscription.CancelEdit();

                // Reset edit mode
                this.CustomerSubscriptionId = 0;

                // Refresh gridview
                BindCustomerSubscription(db, this.CustomerId);

                // Close db connection
                db.Dispose();
            }
            else
            {
                // Customer not yet saved
                throw new InvalidOperationException("Kunde data ikke gemt endnu - kunde abonnement kan derfor ikke oprettes. Venligst gem kundedata først.");
            }
        }

        /// <summary>
        /// Gridview function for updating customer car
        /// </summary>
        protected void gvCar_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            if (this.CustomerId != 0)
            {
                TireServiceDB db = new TireServiceDB();

                // Get id
                this.CarId = Convert.ToInt32(e.Keys["CarId"]);

                // Fecth customer
                Customer customer = db.GetCustomer(this.CustomerId);
                CustomerSubscription customersubscription = db.GetCustomerSubscription(Convert.ToInt32(e.NewValues["CustomerSubscriptionId"]));

                Guid userid = new Guid(Membership.GetUser().ProviderUserKey.ToString());

                // Create car
                Car car = new Car();

                DateTime? lasttiresetchangedate = null;
                DateTime? nexttiresetchangeplanningdate = null;

                string model = "-";
                string enginesize = "-";

                if (e.NewValues["LastTireSetChangeDate"] != null) lasttiresetchangedate = Convert.ToDateTime(e.NewValues["LastTireSetChangeDate"]);
                if (e.NewValues["NextTireSetChangePlanningDate"] != null) nexttiresetchangeplanningdate = Convert.ToDateTime(e.NewValues["NextTireSetChangePlanningDate"]);

                if (e.NewValues["Model"] != null) model = Convert.ToString(e.NewValues["Model"]);
                if (e.NewValues["EngineSize"] != null) enginesize = Convert.ToString(e.NewValues["EngineSize"]);

                CarBLL carBLL = new CarBLL();
                carBLL.UpdateCar(
                                    db,
                                    car,
                                    customersubscription,
                                    customer,
                                    this.CarId,
                                    e.NewValues["RegistrationNumber"].ToString(),
                                    Convert.ToInt32(e.NewValues["CarBrandId"]),
                                    model,
                                    enginesize,
                                    Convert.ToInt32(e.NewValues["FuelType"]),
                                    0 + Convert.ToInt32(e.NewValues["Year"]),
                                    e.NewValues["Color"].ToString(),
                                    Convert.ToInt32(e.NewValues["CarStatusId"]),
                                    lasttiresetchangedate,
                                    nexttiresetchangeplanningdate,
                                    true
                                );

                // Commit changes to database
                db.SubmitChanges();

                // End edit mode
                e.Cancel = true;
                gvCar.CancelEdit();

                // Reset edit mode
                this.CarId = 0;

                // Refresh gridview and dropdownlist
                BindCustomerCar(db, this.CustomerId);

                if (this.CarId == 0)
                {
                    // Refresh tireset gridview
                    BindTireSet(db, this.CustomerId);
                }

                // Close db connection
                db.Dispose();
            }
            else
            {
                // Customer not yet saved
                throw new ArgumentException("Kunde data ikke gemt endnu - kunde bil kan derfor ikke oprettes. Venligst gem kundedata først.");
            }
        }

        /// <summary>
        /// Gridview function for creating customer car
        /// </summary>
        protected void gvCar_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            if (this.CustomerId != 0)
            {
                TireServiceDB db = new TireServiceDB();

                // Set car id to zero - new car
                this.CarId = 0;

                // Fecth customer
                Customer customer = db.GetCustomer(this.CustomerId);
                CustomerSubscription customersubscription = db.GetCustomerSubscription(Convert.ToInt32(e.NewValues["CustomerSubscriptionId"]));

                Guid userid = new Guid(Membership.GetUser().ProviderUserKey.ToString());

                // Create car
                Car car = new Car();

                DateTime? lasttiresetchangedate = null;
                DateTime? nexttiresetchangeplanningdate = null;
                string model = "-";
                string enginesize = "-";

                if (e.NewValues["LastTireSetChangeDate"] != null) lasttiresetchangedate = Convert.ToDateTime(e.NewValues["LastTireSetChangeDate"]);
                if (e.NewValues["NextTireSetChangePlanningDate"] != null) nexttiresetchangeplanningdate = Convert.ToDateTime(e.NewValues["NextTireSetChangePlanningDate"]);

                if (e.NewValues["Model"] != null) model = Convert.ToString(e.NewValues["Model"]);
                if (e.NewValues["EngineSize"] != null) enginesize = Convert.ToString(e.NewValues["EngineSize"]);

                CarBLL carBLL = new CarBLL();
                carBLL.UpdateCar(
                                    db,
                                    car,
                                    customersubscription,
                                    customer,
                                    this.CarId,
                                    e.NewValues["RegistrationNumber"].ToString(),
                                    Convert.ToInt32(e.NewValues["CarBrandId"]),
                                    model,
                                    enginesize,
                                    Convert.ToInt32(e.NewValues["FuelType"]),
                                    0 + Convert.ToInt32(e.NewValues["Year"]),
                                    e.NewValues["Color"].ToString(),
                                    Convert.ToInt32(e.NewValues["CarStatusId"]),
                                    lasttiresetchangedate,
                                    nexttiresetchangeplanningdate,
                                    true
                                );

                if (this.CarId == 0)
                {
                    // Add tiresets for new car
                    TireSet tireset1 = new TireSet();
                    TireSet tireset2 = new TireSet();
                    TireSetBLL tiresetBLL = new TireSetBLL();
                    ContainerCargoRoomBLL containerBLL = new ContainerCargoRoomBLL();
                    
                    // Determine what tires are on the car
                    int tireset1status, tireset2status;
                    int? tireset1container, tireset2container;

                    ASPxRadioButtonList rblCurrentTireSet = (ASPxRadioButtonList)gvCar.FindEditFormTemplateControl("rblCurrentTireSet");

                    if (rblCurrentTireSet.Value.ToString() == "0")
                    {
                        // Winter tires on car
                        tireset1status = (int)Shared.TireSetStatus.OnStock;
                        tireset1container = containerBLL.ReturnNearestContainerCargoRoomId(db, float.Parse(customer.LatitudePrimary.ToString()), float.Parse(customer.LongitudePrimary.ToString()));
                        tireset2status = (int)Shared.TireSetStatus.MountedOnCar;
                        tireset2container = null;
                    }
                    else
                    {
                        // Summer tires on car
                        tireset1status = (int)Shared.TireSetStatus.MountedOnCar;
                        tireset1container = null;
                        tireset2status = (int)Shared.TireSetStatus.OnStock;
                        tireset2container = containerBLL.ReturnNearestContainerCargoRoomId(db, float.Parse(customer.LatitudePrimary.ToString()), float.Parse(customer.LongitudePrimary.ToString()));
                    }

                    tiresetBLL.UpdateTireSet(
                                        db,
                                        tireset1,
                                        car,
                                        (int)Shared.TireType.SummerTires,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        false,
                                        false,
                                        false,
                                        false,
                                        false,
                                        null,
                                        null,
                                        tireset1status,
                                        null,
                                        tireset1container,
                                        true,
                                        false,
                                        null,
                                        userid,
                                        null,
                                        true
                                    );

                    tiresetBLL.UpdateTireSet(
                                        db,
                                        tireset2,
                                        car,
                                        (int)Shared.TireType.WinterTires,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        false,
                                        false,
                                        false,
                                        false,
                                        false,
                                        null,
                                        null,
                                        tireset2status,
                                        null,
                                        tireset2container,
                                        true,
                                        false,
                                        null,
                                        userid,
                                        null,
                                        true
                                    );
                }

                // Commit changes to database
                db.SubmitChanges();

                // End edit mode
                e.Cancel = true;
                gvCar.CancelEdit();

                // Reset edit mode
                this.CarId = 0;

                // Refresh gridview and dropdownlist
                BindCustomerCar(db, this.CustomerId);

                if (this.CarId == 0)
                {
                    // Refresh tireset gridview
                    BindTireSet(db, this.CustomerId);
                }

                // Close db connection
                db.Dispose();
            }
            else
            {
                // Customer not yet saved
                throw new ArgumentException("Kunde data ikke gemt endnu - kunde bil kan derfor ikke oprettes. Venligst gem kundedata først.");
            }
        }

        /// <summary>
        /// Gridview function for updating customer tireset
        /// </summary>
        protected void gvTireSet_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            if (this.CustomerId != 0)
            {
                if (e.NewValues["CarId"] == null)
                {
                    throw new ArgumentException("Bil skal oprettes/vælges før hjulsæt kan oprettes/redigeres.");
                }

                // Get id
                this.TireSetId = Convert.ToInt32(e.Keys["TireSetId"]);

                TireServiceDB db = new TireServiceDB();

                TireSet tireset = new TireSet();

                // Instantiate business layer
                TireSetLogBLL bll = new TireSetLogBLL();

                // Fecth existing customer tireset
                tireset = db.GetTireSet(this.TireSetId);

                if (tireset != null)
                {
                    int fromtiresetstatus = tireset.TireSetStatusId;

                    tireset.CarId = Convert.ToInt32(e.NewValues["CarId"]);
                    tireset.TireTypeId = Convert.ToInt32(e.NewValues["TireTypeId"]);
                    tireset.Size = Convert.ToDecimal(e.NewValues["Size"]);
                    tireset.Width = Convert.ToDecimal(e.NewValues["Width"]);
                    tireset.Height = Convert.ToDecimal(e.NewValues["Height"]);
                    tireset.TireSpeedIndexId = Convert.ToInt32(e.NewValues["TireSpeedIndexId"]);
                    tireset.TireLoadIndexId = Convert.ToInt32(e.NewValues["TireLoadIndexId"]);
                    tireset.TireBrandId = Convert.ToInt32(e.NewValues["TireBrandId"]);
                    tireset.TireBrandNote = e.NewValues["TireBrandNote"].ToString();
                    tireset.LockingBolt = Convert.ToBoolean(e.NewValues["LockingBolt"]);
                    tireset.HubCaps = Convert.ToBoolean(e.NewValues["HubCaps"]);
                    tireset.RunFlatTire = Convert.ToBoolean(e.NewValues["RunFlatTire"]);
                    tireset.RimProtection = Convert.ToBoolean(e.NewValues["RimProtection"]);
                    tireset.ExtraBolts = Convert.ToBoolean(e.NewValues["ExtraBolts"]);
                    tireset.ManufactureDate = Convert.ToDateTime(e.NewValues["ManufactureDate"]);
                    tireset.TireSetStatusId = Convert.ToInt32(e.NewValues["TireSetStatusId"]);
                    tireset.SocketWrenchSize = Convert.ToInt32(e.NewValues["SocketWrenchSize"]);

                    // Create tireset log
                    bll.CreateTireSetLog(db, tireset, DateTime.Now, fromtiresetstatus, tireset.TireSetStatusId, new Guid(Membership.GetUser().ProviderUserKey.ToString()), null, null, null, null, null, tireset.ContainerCargoRoomId);
                }
                else
                {
                    // Customer subscription does not exists
                    throw new ArgumentException("Hjulsæt eksistere ikke");
                }

                // Commit changes to database
                db.SubmitChanges();

                // End edit mode
                e.Cancel = true;
                gvTireSet.CancelEdit();

                // Reset edit mode
                this.TireSetId = 0;

                // Refresh gridview
                BindTireSet(db, this.CustomerId);

                // Close db connection
                db.Dispose();
            }
            else
            {
                // Customer not yet saved
                throw new ArgumentException("Kunde data ikke gemt endnu - hjulsæt kan derfor ikke oprettes. Venligst gem kundedata først.");
            }
        }

        /// <summary>
        /// Gridview function for creating customer tireset
        /// </summary>
        protected void gvTireSet_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            if (this.CustomerId != 0)
            {
                // Set id
                this.TireSetId = 0;

                TireServiceDB db = new TireServiceDB();

                TireSet tireset = new TireSet();

                // Instantiate business layer
                TireSetLogBLL bll = new TireSetLogBLL();

                // Create new tireset
                tireset.CarId = Convert.ToInt32(e.NewValues["CarId"]);
                tireset.TireTypeId = Convert.ToInt32(e.NewValues["TireTypeId"]);
                tireset.Size = Convert.ToDecimal(e.NewValues["Size"]);
                tireset.Width = Convert.ToDecimal(e.NewValues["Width"]);
                tireset.Height = Convert.ToDecimal(e.NewValues["Height"]);
                tireset.TireSpeedIndexId = Convert.ToInt32(e.NewValues["TireSpeedIndexId"]);
                tireset.TireLoadIndexId = Convert.ToInt32(e.NewValues["TireLoadIndexId"]);
                tireset.TireBrandId = Convert.ToInt32(e.NewValues["TireBrandId"]);
                tireset.TireBrandNote = e.NewValues["TireBrandNote"].ToString();
                tireset.LockingBolt = Convert.ToBoolean(e.NewValues["LockingBolt"]);
                tireset.HubCaps = Convert.ToBoolean(e.NewValues["HubCaps"]);
                tireset.RunFlatTire = Convert.ToBoolean(e.NewValues["RunFlatTire"]);
                tireset.RimProtection = Convert.ToBoolean(e.NewValues["RimProtection"]);
                tireset.ExtraBolts = Convert.ToBoolean(e.NewValues["ExtraBolts"]);
                tireset.ManufactureDate = Convert.ToDateTime(e.NewValues["ManufactureDate"]);
                tireset.TireSetStatusId = Convert.ToInt32(e.NewValues["TireSetStatusId"]);
                tireset.SocketWrenchSize = Convert.ToInt32(e.NewValues["SocketWrenchSize"]);

                // Add to database
                db.AddTireSet(tireset);

                // Create tireset log
                bll.CreateTireSetLog(db, tireset, DateTime.Now, null, tireset.TireSetStatusId, new Guid(Membership.GetUser().ProviderUserKey.ToString()), null, null, null, null, null, tireset.ContainerCargoRoomId);

                // Commit changes to database
                db.SubmitChanges();

                // End edit mode
                e.Cancel = true;
                gvTireSet.CancelEdit();

                // Reset edit mode
                this.TireSetId = 0;

                // Refresh gridview
                BindTireSet(db, this.CustomerId);

                // Close db connection
                db.Dispose();
            }
            else
            {
                // Customer not yet saved
                throw new ArgumentException("Kunde data ikke gemt endnu - hjulsæt kan derfor ikke oprettes. Venligst gem kundedata først.");
            }
        }

        #endregion

    }
}